<?php

class ProcMessage {
	protected $_mque = null;
	const MAX_SIZE = 4096;

	public function __construct($id, $perms = 0664) {
		$this->_mque = msg_get_queue($id, $perms);
	}

	public function __destruct() {
	}

	public function send($var, $msgtype=0 ) {
		$error = 0;
		$blocking = true;
		$src_pid = posix_getpid();

		$r = msg_send($this->_mque, 
					$msgtype, 
					array('src'=> $src_pid , 
						'data' => $var),
					true, $blocking, $error );
		if(!$r) {
			throw new Exception("ProcMessage::send error code : $error");
		}
		return true;
	}

	public function receive($desiredmsgtype = 0) {
		$var = null;
		$r = msg_receive( 
			$this->_mque, 
			$desiredmsgtype,
			$rmsg_type, self::MAX_SIZE, 
			$var, 
			true, 
			MSG_IPC_NOWAIT , 
			$error );
		if(!$r) {
			if($error != MSG_ENOMSG)throw new Exception("ProcMessage::receive error code : $error");
		}
		return $var;
	}

	public function stat() {
		return msg_stat_queue($this->_mque);
	}

	public function destruct() {
		return msg_remove_queue($this->_mque);
	}
}
